package tcl.loan.system.web;

import org.apache.shiro.SecurityUtils;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by linjianding on 2016/12/5.
 */
public abstract class ControllerBase {
    /**
     * 取出Shiro中的当前用户UserName.
     */
    public static String getCurrentUserName() {
        String userName = (String) SecurityUtils.getSubject().getPrincipal();
        if (userName != null) {
            return userName;
        } else {
            return null;
        }
    }
    /**
     * 判断ajax请求
     * @param request
     * @return
     */
    protected  boolean isAjax(HttpServletRequest request)
    {
        return  (request.getHeader("X-Requested-With") != null  &&
                "XMLHttpRequest".equals( request.getHeader("X-Requested-With").toString())   ) ;
    }


//    protected <T> PageModel<T> buildPage(ServletRequest request) {
//        int offset = getInt(request, "offset", 0);
//        int limit = getInt(request, "limit", Integer.valueOf(PAGE_SIZE));
//
//        String order = request.getParameter("order");
//        String sortName = request.getParameter("sort");
//        PageModel<T> pageModel = new PageModel<>();
//        pageModel.setOrder(order);
//        pageModel.setSortName(sortName);
//        pageModel.setPageNum((offset / 10) + 1);
//        pageModel.setPageSize(limit);
//        return pageModel;
//    }

    /**
     * 取得整数类型的参数值
        *
     * @param request    HTTP请求
     * @param paramName  参数名称
     * @param defaultInt 如果值为NULL，则返回该默认值
     * @return 整数值
     */
    protected int getInt(ServletRequest request, String paramName, int defaultInt) {
        int ret = 0;
        String temp = request.getParameter(paramName);
        try {
            if (temp == null) {
                ret = defaultInt;
            } else {
                ret = Integer.parseInt(temp);
            }
        } catch (NumberFormatException e) {
            ret = defaultInt;
            e.printStackTrace();
        }
        return ret;
    }
}
